<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/26 0026
 * Time: 上午 9:46
 */
namespace app\api\controller;

use app\common\Helper;
use app\common\lib\Map;
use app\common\lib\Wx;
use app\common\model\Qrcodeciphertext;
use app\common\model\Storesettlerule;
use app\common\model\Userfocus;
use app\common\model\Userinstore;
use app\common\model\Userinstorecount;
use think\Db;
use think\Exception;
use think\Request;

class Common extends Base{
    //店铺搜索
    public function searchStore(Request $request){
        $param = $request->param();
        if(empty($param['lat']) || empty($param['lng']) || empty($param['name'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $StoreList = \app\admin\model\Store::where('status',1)->where('name','like','%'.$param['name'].'%')->select();
        if(!empty($StoreList)){
            $stores = self::LatLngsort($param['lat'],$param['lng'],$StoreList);
            return show(config('status.SUCCESS_STATUS'),'ok',$stores);
        }else{
            return show(config('status.SUCCESS_STATUS'),'ok',[]);
        }
    }

    //店铺关注/取消关注

    public function focusStore(Request $request){
        $param = $request->param();
        if(empty($param['storeId']) || empty($param['userId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $where['userId'] = $param['userId'];
        $where['storeId'] = $param['storeId'];
        $Userfocus = Userfocus::where($where)->find();
        if(!$Userfocus){
            //添加关注
            $UserfocusModel = new Userfocus();
            $UserfocusModel->userId = $param['userId'];
            $UserfocusModel->storeId = $param['storeId'];
            $UserfocusModel->focusTime = date('Y-m-d H:i:s',time());
            $UserfocusModel->save();

        }else{
            //取消关注
            $Userfocus->delete();
        }
        return show(config('status.SUCCESS_STATUS'),'ok',1);
    }






    //根据经纬度对店铺进行排序
    public static function LatLngsort($lat,$lng,$StoreList){
        $stores = [];
        for($i=0;$i<count($StoreList);$i++){
            $distance = (float)Helper::getDistance($lat,$lng,$StoreList[$i]);
            $res = Home::getinstoreAndcountFocus($StoreList[$i]['id']);
            $StoreList[$i]['countInStore'] = $res['countInStore'];
            $StoreList[$i]['countFocus'] = $res['countFocus'];
            $StoreList[$i]['distance'] = $distance;
            $Ticket = Home::getTicket($StoreList[$i]['id']);
            if($Ticket){
                $StoreList[$i]['Ticket'] = $Ticket['name'];
                $StoreList[$i]['TicketId'] = $Ticket['id'];
            }else{
                $StoreList[$i]['Ticket'] = '';
            }

            array_push($stores,$StoreList[$i]);
        }
        foreach ($stores as $k=>$v){
            $dos[$k] = $v['distance'];
        }
        array_multisort($dos, SORT_ASC, $stores);
        return $stores;
    }

    //进店数量统计
    public function addInStore(Request $request){
        $param = $request->param();
        if(empty($param['storeId']) || empty($param['userId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        Db::startTrans();
        try{
            $Store = \app\admin\model\Store::get($param['storeId']);
            $Store->setInc('inStoreCount',1);
            $Userinstore = Userinstore::where(['storeId'=>$param['storeId'],'userId'=>$param['userId']])->find();
            if($Userinstore){
                $Userinstore->inStoreTime = date('Y-m-d H:i:s',time());
                $Userinstore->save();
                $Userinstore->setInc('inStoreCount',1);
            }else{
                $UserinstoreModel = new Userinstore();
                $UserinstoreModel->userId = $param['userId'];
                $UserinstoreModel->storeId = $param['storeId'];
                $UserinstoreModel->inStoreStatus = 1;
                $UserinstoreModel->inStoreCount = 1;
                $UserinstoreModel->inStoreTime = date('Y-m-d H:i:s',time());
                $UserinstoreModel->save();
            }
            $Userinstorecount = Userinstorecount::where(['storeId'=>$param['storeId'],'userId'=>$param['userId']])->whereTime('inStoreTime','today')->find();
            if($Userinstorecount){
                $Userinstorecount->setInc('inStoreCount',1);
            }else{
                $UserinstorecountModel = new Userinstorecount();
                $UserinstorecountModel->userId = $param['userId'];
                $UserinstorecountModel->storeId = $param['storeId'];
                $UserinstorecountModel->inStoreCount = 1;
                $UserinstorecountModel->inStoreTime = date('Y-m-d H:i:s',time());
                $UserinstorecountModel->save();
            }
            Db::commit();
            return show(config('status.SUCCESS_STATUS'),'ok',1);
        }catch (Exception $ex){
            Db::rollback();
        }

    }

    //优惠券二维码、海报分享信息
    public function shareInfo(Request $request){
        $param = $request->param();
        if(empty($param['ticketId']) || empty($param['storeId']) || empty($param['userId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $Qrcodeciphertext = Qrcodeciphertext::where(['ticketId'=>$param['ticketId'],'userId'=>$param['userId']])->find();
        if($Qrcodeciphertext && $Qrcodeciphertext->qrcode_img){
            $img_url = $Qrcodeciphertext->qrcode_img;
        }else{
            $id = Helper::getUUID22();
            $img_url = Wx::getTicketCode($id);
            $QrcodeciphertextModel = new Qrcodeciphertext();
            $QrcodeciphertextModel->id = $id;
            $QrcodeciphertextModel->ticketId = $param['ticketId'];
            $QrcodeciphertextModel->storeId = $param['storeId'];
            $QrcodeciphertextModel->userId = $param['userId'];
            $QrcodeciphertextModel->qrcode_img = $img_url;
            $QrcodeciphertextModel->save();
        }

        $store = \app\admin\model\Store::get($param['storeId']);
        $ticket = \app\admin\model\Ticket::get($param['ticketId']);
        $user = \app\common\model\User::get($param['userId']);

        $data['qrCode'] = $img_url;
        $data['store'] = $store;
        $data['ticket'] = $ticket;
        $data['user'] = $user;

        return show(config('status.SUCCESS_STATUS'),'ok',$data);


    }

    //根据id解密出优惠券二维码信息
    public function getShareId(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $Qrcodeciphertext = Qrcodeciphertext::get($param['id']);
        if($Qrcodeciphertext){
            $data['storeId'] = $Qrcodeciphertext->storeId;
            $data['ticketId'] = $Qrcodeciphertext->ticketId;
            $data['userId'] = $Qrcodeciphertext->userId;

            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }else{
            return show(2,'信息为空',null);
        }
    }

    public function getaddress($lat,$lng){
        if(empty($lat) || empty($lng)){
            return show(config('status.ERROR_STATUS'),'缺少经纬度','缺少经纬度');
        }
        $res =  Map::geocoder($lat.','.$lng);
        return show(config('status.SUCCESS_STATUS'),'ok',$res);
    }

    //获取平台设置信息
    public function getPlatRule(){
        $Storesettlerule = Storesettlerule::where(true)->find();
        if($Storesettlerule){
            $royaltyRate = (int)$Storesettlerule->royaltyRate;
            return show(config('status.SUCCESS_STATUS'),'ok',$royaltyRate);
        }else{
            return show(2,'暂无数据',null);
        }
    }
}